package com.tanhua.server.service;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.PageUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.commons.utils.UserHolder;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.VideoVo;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SmallVideosService {
    @DubboReference
    private VideoApi videoApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private FastFileStorageClient storageClient;

    @Autowired
    private FdfsWebServer webServer;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private MqMessageService mqMessageService;



    //发布视频
    @CacheEvict(value="videoList",allEntries = true)
    public void saveVidos(MultipartFile videoThumbnail, MultipartFile videoFile) throws IOException {
//        mqMessageService.sendLogMessage(UserHolder.getUserId(),"0301","video",null);

        //1、封面图上传到阿里云OSS，获取地址
        String upload = ossTemplate.upload(videoThumbnail.getOriginalFilename(), videoThumbnail.getInputStream());//图片存阿里云oss
        //2、视频上传到fdfs上，获取请求地址
        String originalFilename = videoFile.getOriginalFilename();
        //获取文件的后缀名
        String substring = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        //文件输入流，文件长度，文件后缀，元数据
        StorePath storePath = storageClient.uploadFile(videoFile.getInputStream(), videoFile.getSize(), substring, null);
        String videoUrl=webServer.getWebServerUrl()+ storePath.getFullPath();                       //http://192.168.136.160:8888/
        //3、创建Video对象，并设置属性
        Video video=new Video();
        video.setUserId(UserHolder.getUserId());
        video.setPicUrl(upload);
        video.setVideoUrl(videoUrl);
        video.setCreated(System.currentTimeMillis());
        video.setText("我是傻逼");
           videoApi.save(video);


        //4、调用API完成保存

    }
    //查找视频先从大数据查
    @Cacheable(value="videoList",key="#page + '_' +  #pagesize")
    public PageResult findByVideos(Integer page, Integer pagesize) {

        Long userId = UserHolder.getUserId();
        String key =Constants.VIDEOS_RECOMMEND+userId;
        String vid = redisTemplate.opsForValue().get(key);
        List<Video> list=new ArrayList<>();
        int redisPage =0;
        if(!StringUtils.isEmpty(vid)){
            //如果不为空
            String[] vids = vid.split(",");
            //判断当前页的起始条数是否小于数组总数
            if(((page-1)*pagesize)<vid.length()){
                List<Long> vids1 = Arrays.stream(vids).skip((page - 1) * pagesize).limit(pagesize)
                        .map(e -> Long.valueOf(e))
                        .collect(Collectors.toList());
                list= videoApi.findVideosByPids(vids1);//拿到数据
            }
            redisPage=PageUtil.totalPage(vids.length,pagesize);
        }
        if(list.isEmpty()){
          list=  videoApi.queryVideos(page-redisPage,pagesize);
        }
        List<Long> userId1 = CollUtil.getFieldValues(list, "userId", Long.class);
        Map<Long, UserInfo> userInfoMap = userInfoApi.findByIds(userId1, null, null);
        List<VideoVo> vos =new ArrayList<>();
        for (Video video : list) {
            UserInfo userInfo = userInfoMap.get(video.getUserId());
            if(userInfo!=null){
                VideoVo init = VideoVo.init(userInfo, video);
                //判断是否已经喜欢
                String Videokey1 =Constants.VIDEO_LIKE_HASHKEY+userId;
                String hashKey1=userInfo.getId().toString();
                String flag1 =(String) redisTemplate.opsForHash().get(Videokey1, hashKey1);
                if(!StringUtils.isEmpty(flag1)){
                    init.setHasLiked(1);
                }
                //判断是否已经关注
                String Videokey2 =Constants.FOCUS_USER+userId;
                String hashKey2=userInfo.getId().toString();
                String flag2 =(String) redisTemplate.opsForHash().get(Videokey2,hashKey2);
                if(!StringUtils.isEmpty(flag2)){
                    init.setHasFocus(1);
                }
                vos.add(init);

            }
        }
        return new PageResult(page,pagesize,0,vos);
    }
}
